import {action, observable, runInAction} from "mobx";
import {BaseResInterface, sendGetRequest} from "../../../net";
import {realm} from "../../../dao";
import * as _ from 'lodash'
import {defaultArr, isSameDate} from "../../../util";
import Collection = Realm.Collection;
import {ProductStore} from "./product";

interface BannerResInterface extends BaseResInterface {
    data: Banner[]
}

export interface Banner {
    id: number;
    imageUrl: string;
    productId: number;
    categoryId: number
}


export class BannerStore {
    @observable bannerList: Banner[] = [];
    storeBanners: Collection<Banner>;

    constructor() {
        this.storeBanners = realm.objects<Banner>("Banner");
    }

    @action.bound
    async getBanners(categoryId: number) {
        const dbRes = this.storeBanners.filtered(`categoryId = ${categoryId}`);
        this.bannerList = _.toArray(dbRes);

        const {data = []} = await sendGetRequest<BannerResInterface>("main/getBanners", {categoryId});
        runInAction(() => {
            this.bannerList = data;
        });
        realm.write(() => {
            data.forEach((banner) => {
                realm.create<Banner>("Banner", banner, true);
            })
        });
    }
}

export function getBannerStoreInstance() {
    return new BannerStore();
}

const BannerStoreInstance = getBannerStoreInstance();
export default BannerStoreInstance